package com.dindang.ddm.mvp.presenter;

import android.app.Application;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.dindang.ddm.R;
import com.dindang.ddm.app.AppConst;
import com.dindang.ddm.mvp.contract.HomeContract;
import com.dindang.ddm.mvp.model.entity.NewsList;
import com.dindang.ddm.mvp.model.entity.Work;
import com.dindang.ddm.mvp.ui.adapter.custom.AutoPollAdapter;
import com.dindang.ddm.mvp.ui.adapter.custom.WorkViewAdapter;
import com.dindang.ddm.mvp.ui.adapter.multitype.LabelViewBinder;
import com.dindang.ddm.mvp.ui.adapter.multitype.NewViewBinder;
import com.dindang.ddm.mvp.ui.adapter.multitype.WorkViewBinder;
import com.dindang.ddm.mvp.ui.listener.AdapterListener;
import com.dindang.ddm.mvp.ui.manager.FullyGridLayoutManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.model.LoginEvent;
import com.luck.picture.lib.decoration.RecycleViewDivider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;


@FragmentScope
public class HomePresenter extends BasePresenter<HomeContract.Model, HomeContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    WorkViewAdapter workViewAdapter;
    AutoPollAdapter newsAdapter;
    WorkViewAdapter workViewAdapter2;
    WorkViewAdapter workViewAdapter3;

    List<Work> list = new ArrayList<>();
    List<NewsList.News> news = new ArrayList<>();
    List<Work> list2 = new ArrayList<>();
    List<Work> list3 = new ArrayList<>();

    private boolean isFirst = true;
    private MultiTypeAdapter mAdapter;
    private Items mItems = new Items();
    private int SPAN_COUNT = 4;

    @Inject
    public HomePresenter(HomeContract.Model model, HomeContract.View rootView) {
        super(model, rootView);
    }

    public void initView() {
//        initAdapter();
        mRootView.getToolbarTitle().setText("工作台");
    }

    private void initAdapter() {
        if(mAdapter == null){
            mAdapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            mAdapter.register(String.class, new LabelViewBinder());
            mAdapter.register(NewsList.class, new NewViewBinder(listener));
            mAdapter.register(Work.class, new WorkViewBinder(listener));
            final GridLayoutManager layoutManager = new GridLayoutManager(mRootView.getFragment().getActivity(), SPAN_COUNT);
            GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    Object item = mItems.get(position);
                    if (item instanceof String) {
                        return 4;
                    }
                    if (item instanceof Work) {
                        return 1;
                    }
                    return SPAN_COUNT;
                }
            };
            layoutManager.setSpanSizeLookup(spanSizeLookup);
            mAdapter.setItems(mItems);
            mRootView.getRecyclerview().setLayoutManager(layoutManager);
            mRootView.getRecyclerview().setAdapter(mAdapter);
        }
    }

    public void initListener() {
        initPtrFrame();
    }

    public void initDate() {
        if(!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        if(isFirst){
            LogUtils.debugInfo("Contact页面重新加载");
            isFirst = false;
            initTool();
        }
    }

    private void initPtrFrame() {
//        mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.REFRESH);
//        mRootView.getPtrclassicframelayout().disableWhenHorizontalMove(true);
//        mRootView.getPtrclassicframelayout().setLastUpdateTimeRelateObject(this);
//        mRootView.getPtrclassicframelayout().setPtrHandler(new PtrDefaultHandler2() {
//            @Override
//            public void onLoadMoreBegin(PtrFrameLayout frame) {
//            }
//
//            @Override
//            public void onRefreshBegin(PtrFrameLayout frame) {
//                mRootView.getEmptylayout().setEmptyStatus(EmptyLayout.STATUS_LOADING);
//                //下拉刷新
//                mRootView.getPtrclassicframelayout().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        initTool();
//                    }
//                },2000);
//            }
//
//            @Override
//            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
//                return super.checkCanDoRefresh(frame, content, header);
//            }
//
//            @Override
//            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
//                return super.checkCanDoLoadMore(frame, content, footer);
//            }
//        });
    }

    /**
     * 请求工具接口
     */
    private void initTool() {

        news.clear();
        list2.clear();
        list3.clear();

        mRootView.getEmptylayout().hide();

        news.add(new NewsList.News(1, "欢迎使用app"));
        news.add(new NewsList.News(2, "这样很好"));
        news.add(new NewsList.News(3, "test"));
        mRootView.getAutoPollRecyclerView().setLayoutManager(new LinearLayoutManager(mRootView.getAutoPollRecyclerView().getContext(), LinearLayoutManager.VERTICAL, false));
        newsAdapter = new AutoPollAdapter(mRootView.getAutoPollRecyclerView().getContext(), news);
        mRootView.getAutoPollRecyclerView().setAdapter(newsAdapter);
        mRootView.getAutoPollRecyclerView().start();

        list2.add(new Work(R.mipmap.ic_home_rwgl, 0, "/propertyfee/activity/PropertyFeeActivity", "物业收费", 1, 1, 2));
        list2.add(new Work(R.mipmap.ic_home_wxgl, 0, "/maintenance/activity/MaintainManagementActivity", "维修管理", 1, 2, 2));
        list2.add(new Work(R.mipmap.xunjian1, 0, "/checkline/TaskDetailActivity", "安保巡检", 1, 3, 2));
        workViewAdapter2 = new WorkViewAdapter(list2).setListener(new WorkViewAdapter.OnClickListener() {
            @Override
            public void onClick(int position) {
                if(null == BaseAppConst.accountInfo){
                    ARouter.getInstance().build("/activity/LoginActivity").navigation(mAppManager.getCurrentActivity());
                    return;
                }
                Work work = list2.get(position);
                if(!TextUtils.isEmpty(work.getActivity())){
                    ARouter.getInstance().build(work.getActivity()).navigation();
                }else{
                    ArmsUtils.makeText(mApplication, "正在开发中...");
                }
            }
        });

        list3.add(new Work(R.mipmap.ic_home_znbb, 0, "", "智能报表", 1, 1, 3));
        workViewAdapter3 = new WorkViewAdapter(list3).setListener(new WorkViewAdapter.OnClickListener() {
            @Override
            public void onClick(int position) {
                if(null == BaseAppConst.accountInfo){
                    ARouter.getInstance().build("/activity/LoginActivity").navigation(mAppManager.getCurrentActivity());
                    return;
                }
                Work work = list3.get(position);
                if(!TextUtils.isEmpty(work.getActivity())){
                    ARouter.getInstance().build(work.getActivity()).navigation();
                }else{
                    ArmsUtils.makeText(mApplication, "正在开发中...");
                }
            }
        });

        mRootView.getRecyclerview().setAdapter(workViewAdapter2);
        mRootView.getRecyclerview2().setAdapter(workViewAdapter3);
    }

    AdapterListener listener = new AdapterListener() {
        @Override
        public void onClick(int position) {
            Work work = (Work) mItems.get(position);
            if(!TextUtils.isEmpty(work.getActivity())){
                ARouter.getInstance().build(work.getActivity()).navigation();
            }else{
                ArmsUtils.makeText(mApplication, "正在开发中...");
            }
        }

        @Override
        public void onDelete(int position) {

        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        this.mAdapter = null;
        this.mItems = null;
        this.listener = null;
        this.list = null;
        this.news = null;
        this.list2 = null;
        this.list3 = null;
        this.workViewAdapter = null;
        this.newsAdapter = null;
        this.workViewAdapter2 = null;
        this.workViewAdapter3 = null;

        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccess(LoginEvent loginEvent){
        if(!isFirst) {
            isFirst = true;
            initDate();
        }
    }
}
